package com.atguigu.eduservice.service.impl;

import com.atguigu.eduservice.entity.EduChapter;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.entity.chactVo.ChapterVo;
import com.atguigu.eduservice.entity.chactVo.VideoVo;
import com.atguigu.eduservice.mapper.EduChapterMapper;
import com.atguigu.eduservice.service.EduChapterService;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.Myexception.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author lhl
 * @since 2022-07-04
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
    @Resource
    EduVideoService videoService;
    @Override
    public List<ChapterVo> nestedList(String courseId) {
        // 首先查询章节信息
        QueryWrapper<EduChapter> chapterWrapper = new QueryWrapper<>();
        chapterWrapper.eq("course_id",courseId);
        // 所有课程对应的章节信息
        List<EduChapter> eduChapters = baseMapper.selectList(chapterWrapper);
        ArrayList<ChapterVo> resData = new ArrayList<>();
        // 获取小节信息
        QueryWrapper<EduVideo> videoWrapper = new QueryWrapper<>();

        List<EduVideo> videoList = videoService.list(videoWrapper);
        // 遍历 随后进行封装
        eduChapters.forEach((item)->{
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(item,chapterVo);
            resData.add(chapterVo);
            ArrayList<VideoVo> videoVos = new ArrayList<>();
            videoList.forEach((viItem)->{
                if(viItem.getChapterId().equals(item.getId())){
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(viItem,videoVo);
                    videoVos.add(videoVo);
                }
            });
            chapterVo.setChildren(videoVos);
        });

        return resData;
    }

    @Override
    public boolean deleteChapter(String id) {
        QueryWrapper<EduVideo> eduVideoQueryWrapper = new QueryWrapper<>();
        eduVideoQueryWrapper.eq("chapter_id",id);
        int count = videoService.count(eduVideoQueryWrapper);
        if(count>0){
            throw new GuliException(20001,"该章节下面有小节,不可以删除");
        }
        boolean b = this.removeById(id);
        return b;
    }

    @Override
    public void removeChapById(String id) {
        QueryWrapper<EduChapter> eduChapterQueryWrapper = new QueryWrapper<>();
        eduChapterQueryWrapper.eq("course_id",id);
        this.remove(eduChapterQueryWrapper);
    }
}
